package com.fsnbigdata.web;
import com.fsnbigdata.domain.Park;
import com.fsnbigdata.domain.Vegetation;
import com.fsnbigdata.domain.dto.NamingPair;
import com.fsnbigdata.domain.query.ParkQueryDslBinder;
import com.fsnbigdata.domain.query.VegetationQueryDslBinder;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import com.fsnbigdata.util.SortTools;
import com.querydsl.core.types.Predicate;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.VegetationService;
import io.springlets.data.domain.GlobalSearch;

import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

/**
 * = VegetationsCollectionJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Vegetation.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/vegetations", name = "VegetationsCollectionJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Vegetation", description = "植被" )
public class VegetationsCollectionJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    private VegetationService vegetationService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param vegetationService
     */
    @Autowired
    public VegetationsCollectionJsonController(VegetationService vegetationService) {
        this.vegetationService = vegetationService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return VegetationService
     */
    public VegetationService getVegetationService() {
        return vegetationService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetationService
     */
    public void setVegetationService(VegetationService vegetationService) {
        this.vegetationService = vegetationService;
    }

    @GetMapping(name = "index", value = "index")
    public ResponseEntity<List<NamingPair>> category(
        @ApiParam @RequestParam(required = false) String initial) {
        List<NamingPair> namingPairs = getVegetationService().findAllByInitial(initial);
        return ResponseEntity.ok(namingPairs);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param query
     * @param pageable
     * @return ResponseEntity
     */
    @GetMapping(name = "search", value = "search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Vegetation>> search(
            @ApiParam @RequestParam(required = false) String query,
            Pageable pageable) {
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        Page<Vegetation> vegetations = getVegetationService().findAll(globalSearch, pageable);
        return ResponseEntity.ok(vegetations);
    }

    /**
     *
     * @param predicate
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "advanceSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Vegetation>> advanceSearch(
            @ApiParam @QuerydslPredicate(root = Vegetation.class, bindings = VegetationQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Page<Vegetation> vegetations = getVegetationService().search(predicate, pageable);
        return ResponseEntity.ok(vegetations);
    }

    /**
     * 查询部分信息
     *
     * @return
     */
    @GetMapping(name = "search", value = "query")
    public List<List<Vegetation>> query() {
        //返回全部数据
        return getVegetationService().findAllByCategory();
    }

    /**
     * 自定义搜索
     * @param
     * @param
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "customSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public List getList(HttpServletRequest request, Pageable pageable){
        String name = request.getParameter("name");//关键字
        String content = request.getParameter("content");//desc或asc
        String value = request.getParameter("value");//字段名称
        String catagory = request.getParameter("catagory");//分类
        String location = request.getParameter("location");//地区

        List vegetations=null;
        if (StringUtils.isNotEmpty(content)&&StringUtils.isNotEmpty(value)){
            Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort(content,value));
            vegetations=getVegetationService().findByPageAndSize(catagory,location,name,pageable1);
        }else{
            vegetations=getVegetationService().findByPageAndSize(catagory,location,name,pageable);
        }
        return vegetations;
    }
    /**
     * 根据id查询详情
     * @param request
     * @return
     */
    @GetMapping(name = "find" , value="find")
    public Vegetation findById(HttpServletRequest request){
        return getVegetationService().findOne(Long.parseLong(request.getParameter("id")));
    }
    /**
     * 根据id 降序排序
     */
    @GetMapping(name = "search", value = "sortByIdAndDesc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Vegetation>> sortByIdAndDesc(
            @ApiParam @QuerydslPredicate(root = Vegetation.class, bindings = VegetationQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(), SortTools.basicSort("DESC","id"));
        Page<Vegetation> vegetations=getVegetationService().search(predicate, pageable1);
        return ResponseEntity.ok(vegetations);
    }
    /**
     * 根据id 升序排序
     */
    @GetMapping(name = "search", value = "sortByIdAndAsc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Vegetation>> sortByIdAndAsc(
            @ApiParam @QuerydslPredicate(root = Vegetation.class, bindings = VegetationQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort("ASC","id"));
        Page<Vegetation> vegetations=getVegetationService().search(predicate, pageable1);
        return ResponseEntity.ok(vegetations);
    }
    /**
     * TODO Auto-generated method documentation
     *
     * @param query
     * @param pageable
     * @return ResponseEntity
     */
    @GetMapping(name = "list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    @PreAuthorize("hasRole('DB_VEGETATION')")
    public ResponseEntity<Page<Vegetation>> list(
            Authentication authentication,
            @ApiParam @RequestParam(required = false)  String query,
            Pageable pageable) {
        Page<Vegetation> specimens = null;
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        if(!authorities.contains("ROLE_USER_ADMIN")){
            specimens = getVegetationService().findAll(globalSearch, pageable, authentication.getName());
        }else{
            specimens = getVegetationService().findAll(globalSearch, pageable);
        }
        return ResponseEntity.ok(specimens);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return UriComponents
     */
    public static UriComponents listURI() {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(VegetationsCollectionJsonController.class).list( null,null, null)).build().encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetation
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(name = "create")
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiOperation(value = "",notes = "save")
    public ResponseEntity<?> create(
            @Valid @RequestBody Vegetation vegetation,
            BindingResult result,
            Principal principal) throws Exception {
        if (vegetation.getId() != null || vegetation.getVersion() != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        vegetation.getDistribution().forEach(it -> it.setVegetation(vegetation));
        vegetation.getImages().forEach(it -> it.setVegetation(vegetation));
        vegetation.getListQuadrat().forEach(list -> {
            list.setVegetation(vegetation);
            list.getItems().forEach(item -> item.setListQuadrat(list));
        });

        vegetation.setCreator(principal.getName());

        Vegetation newVegetation = getVegetationService().save(vegetation);
        UriComponents showURI = VegetationsItemJsonController.showURI(newVegetation);

        Class<?> clazz = VegetationsCollectionJsonController.class;
        Method method = clazz.getMethod("create", ReflectUtil.getPeremeterClass(clazz, "create"));
        ReflectUtil.setAnnotationOn(method,"新增植被库，名称："+newVegetation.getName());
        return ResponseEntity.ok(newVegetation);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetations
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(value = "/batch", name = "createBatch")
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiIgnore
    public ResponseEntity<?> createBatch(@Valid @RequestBody Collection<Vegetation> vegetations, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }
        getVegetationService().save(vegetations);
        return ResponseEntity.created(listURI().toUri()).build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param vegetations
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(value = "/batch", name = "updateBatch")
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiIgnore
    public ResponseEntity<?> updateBatch(@Valid @RequestBody Collection<Vegetation> vegetations, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }
        getVegetationService().save(vegetations);
        return ResponseEntity.ok().build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ids
     * @return ResponseEntity
     */
    @DeleteMapping(value = "/batch/{ids}", name = "deleteBatch")
    @PreAuthorize("hasRole('DB_VEGETATION')")
    @ApiIgnore
    public ResponseEntity<?> deleteBatch(@PathVariable("ids") Collection<Long> ids) {
        getVegetationService().delete(ids);
        return ResponseEntity.ok().build();
    }


}
